using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.AceEngineering.SPM.SPMCustomDataEntity;
using System.Configuration;
using System.Web;
using Microsoft.AceEngineering.SPM.SPMBusinessLayer;
using System.Text;
using System.Collections;

public partial class ApplicationDataEntryView : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["user"] == null)
            ValidateUser();
        else
        {
            UserCDE userData = (UserCDE)Session["user"];
            if (userData.Time.AddMinutes(Int32.Parse(ConfigurationManager.AppSettings["AbsoluteExpiration"].ToString())) <= DateTime.Now)
                ValidateUser();
        }

        int intAppID = 0;
        bool idExist = Int32.TryParse(Request.QueryString["ID"], out intAppID);
        if (!Page.IsPostBack)
        {
            if (idExist)
            {
                if (Session["appUpd"] != null)
                {
                    Session["appUpd"] = null;
                    Page pge = (Page)this.Page;
                    Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, "Application updated sucessfully", "errorkey");
                }
                pnlSearch.Visible = false;
                pnlApplication.Visible = true;
                
                FillAppInfo(intAppID);
                LCGraphics.LoadAppStatus(intAppID);
            }
            else
            {          
                pnlSearch.Visible = true;
                pnlApplication.Visible = false;
            }

            if (Session["search"] == null)
            {
                btnBack.ToolTip = "Back to View Application Data - Application Quick Search"; 
            }
            else
            {
                btnBack.ToolTip = "Back to Advanced Search";
            }
        }
    }

    private string GiveMeAlias(string domainAndAlias)
    {
        domainAndAlias = domainAndAlias.ToLower();
        char[] strSeperator = new char[] { '\\' };
        string[] aryAuthUser = new string[2];
        aryAuthUser = domainAndAlias.Split(strSeperator);
        return aryAuthUser[1];
    }

    private void ValidateUser()
    {
        string currAlias = GiveMeAlias(HttpContext.Current.User.Identity.Name);
        UserCDE user = UsersBL.ValidateUser(currAlias);
        if (user.Active)
        {
            Session["user"] = user;
            Session["loginname"] = user.UserAlias;
        }
        else
        {
            Response.Redirect(Request.ApplicationPath + "/Errors/NoAccess.htm");
        }
    }

    protected void btnGo_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            int intAppID = Int32.Parse(this.lstApplicationNames.SelectedItem.Value);
            pnlSearch.Visible = false;
            pnlApplication.Visible = true;
            FillAppInfo(intAppID);
            LCGraphics.LoadAppStatus(intAppID);
        }
        else
        {
            StringBuilder msg = new StringBuilder("Please correct the following:\\n");
            foreach (IValidator aValidator in this.Validators)
            {
                if (!aValidator.IsValid)
                {
                    msg.Append("- " + aValidator.ErrorMessage + "\\n");
                }
            }
            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, msg.ToString(), "errorkey");
        }
    }

    protected void Search(string name, int id)
    {
        try
        {
            ArrayList list = ApplicationsBL.GetSearchApplicationData(name, id);

            lstApplicationNames.Items.Clear();
            foreach (ListItem lstTemp in list)
            {
                lstApplicationNames.Items.Add(lstTemp);
            }

            pnlSearch.Visible = true;
            lstApplicationNames.Visible = true;
            lblResult.Visible = true;
            btnGo.Visible = true;
        }
        catch (Exception ex)
        {
            string strErrorType = ex.Message.ToString().Substring(0, 8);

            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.APMErrorHandling(ex, Request.IsLocal, pge, Session, Request);
            if (!Request.IsLocal && strErrorType != "APMError")
            {
                Server.ClearError();
                Server.Transfer(Request.ApplicationPath + "/Errors/GenericErrorPage.htm");
            }
            btnGo.Visible = false;
            lstApplicationNames.Visible = false;
            lblResult.Visible = false;
        }
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            int searchByID;
            int intSearchType = Int32.Parse(rdsearchType.SelectedValue.ToString());

            bool IDFound = Int32.TryParse(txtSearch.Text, out searchByID);
            if (intSearchType == 1)
            {
                try
                {
                    if (IDFound)
                        Search(txtSearch.Text, searchByID);
                    else
                        throw new Exception("APMError021");
                }
                catch (Exception ex)
                {
                    string strErrorType = ex.Message.ToString().Substring(0, 8);

                    Page pge = (Page)this.Page;
                    Microsoft.ACEEngineering.Utility.CommonProcess.APMErrorHandling(ex, Request.IsLocal, pge, Session, Request);
                    if (!Request.IsLocal && strErrorType != "APMError")
                    {
                        Server.ClearError();
                        Server.Transfer(Request.ApplicationPath + "/Errors/GenericErrorPage.htm");
                    }
                }
            }
            else
            {
                Search(txtSearch.Text, 0);
            }
        }
        else
        {
            string msg = "Please correct the following:\\n- Required Field: Application Name/ID";
            Page pge = (Page)this.Page;
            Microsoft.ACEEngineering.Utility.CommonProcess.CreateMessageAlert(ref pge, msg, "errorkey");
        }
    }

    protected void lbview_Click(object sender, EventArgs e)
    {
        Session["search"] = null;
        Response.Redirect("~/Application/ApplicationDataEntryView.aspx");
    }

    protected void lbedit_Click(object sender, EventArgs e)
    {
        Session["search"] = null;
        Response.Redirect("~/Application/ApplicationDataEntry.aspx?action=edit");
    }

    protected void lbnew_Click(object sender, EventArgs e)
    {
        Session["search"] = null;        
        Response.Redirect("~/Application/ApplicationDataEntry.aspx");
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        if (Session["search"] == null)
        {
            Response.Redirect("~/Application/ApplicationDataEntryView.aspx");
        }
        else
        {
            Session["fView"] = "true";
            Response.Redirect("~/Application/Search.aspx");
        }
    }

    private void FillAppInfo(int appID)
    {
        try
        {
            ApplicationCDE appData = ApplicationsBL.GetApplicationDataByID(appID);

            lblVAppID.Text = Microsoft.Security.Application.AntiXss.HtmlEncode(appData.ApplicationID.ToString());
            lblVAppName.Text = Microsoft.Security.Application.AntiXss.HtmlEncode(appData.ApplicationName);
            lblVAppOwner.Text = Microsoft.Security.Application.AntiXss.HtmlEncode(appData.ContactAlias);
            lblVOrgName.Text = Microsoft.Security.Application.AntiXss.HtmlEncode(appData.OrganizationName);

            lblVVersionNumber.Text = Microsoft.Security.Application.AntiXss.HtmlEncode(appData.ApplicationVersion);
            lblVDescription.Text = Microsoft.Security.Application.AntiXss.HtmlEncode(appData.Description);
            lblVStartDate.Text = DateTime.Parse(appData.StartDate.ToString()).ToShortDateString();
            lblVEstimatedCompDate.Text = DateTime.Parse(appData.CompletionDate.ToString()).ToShortDateString();
            if (!string.IsNullOrEmpty(appData.ActualCompletedDate))
                lblVActualCompletedDate.Text = DateTime.Parse(appData.ActualCompletedDate.ToString()).ToShortDateString();

            gvProperty.DataBind();
            gridApplicationContact.DataBind();
        }
        catch
        {
            Session["search"] = null;
            Response.Redirect("~/Application/ApplicationDataEntryView.aspx");
        }
    }

    protected void lnkedit_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Application/ApplicationDataEntry.aspx?action=edit&id=" + lblVAppID.Text);
    }

    protected void lnkCopy_Click(object sender, EventArgs e)
    {
        Session["search"] = null;
        Response.Redirect("~/Application/ApplicationDataEntry.aspx?action=add&id=" + lblVAppID.Text);
    }

    protected void obdsContact_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
    {
        e.InputParameters[0] = Int32.Parse(lblVAppID.Text);
    }

    protected void obdsProperty_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
    {
        e.InputParameters[0] = Int32.Parse(lblVAppID.Text);
    }
}